package com.orderVideo.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orderVideo.dto.UpdatePasswordDTO;
import com.orderVideo.entity.User;
import com.orderVideo.exception.BusinessException;
import com.orderVideo.mapper.UserMapper;
import com.orderVideo.service.UserService;
import com.orderVideo.util.JwtUtil;
import com.orderVideo.utils.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Base64;

/**
 * @author Sakur
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2025-03-27 14:43:48
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
		implements UserService {

	@Value("${video.avatars.path}")
	private String avatarPath;

	@Override
	public User login(String username, String password) {
		LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(User::getUsername, username);
		User user = this.getOne(wrapper);

		if (user == null || !user.getPassword().equals(password)) {
			throw new RuntimeException("用户名或密码错误");
		}

		// 生成token
		user.setToken(JwtUtil.generateToken(user.getUserId()));
		return user;
	}

	@Override
	public User register(User user) {
		// 检查用户名是否已存在
		if (lambdaQuery().eq(User::getUsername, user.getUsername()).exists()) {
			throw new RuntimeException("用户名已存在");
		}

		// 设置默认角色为普通用户
		user.setUserType("user");

		// 保存用户
		this.save(user);

		// 生成token
		user.setToken(JwtUtil.generateToken(user.getUserId()));
		return user;
	}

	@Override
	public boolean updatePassword(UpdatePasswordDTO dto) {
//		// 获取操作者信息
//		User operator = getById(LoginUser.getUserId());
//		if (operator == null) {
//			throw new RuntimeException("操作者不存在");
//		}
//
//		// 获取要修改密码的用户信息
//		User targetUser = getById(dto.getUserId());
//		if (targetUser == null) {
//			throw new RuntimeException("用户不存在");
//		}
//
//		// 判断操作类型
//		boolean isAdmin = "admin".equals(operator.getUserType());
//		boolean isSelfOperation = dto.getUserId().equals(operator.getUserId());
//
//		// 权限校验和密码验证
//		if (isAdmin) {
//			// 管理员操作
//			if (isSelfOperation) {
//				// 管理员修改自己密码时，如果传了旧密码需要验证
//				if (dto.getOldPassword() != null &&
//						!dto.getOldPassword().equals(targetUser.getPassword())) {
//					throw new RuntimeException("旧密码错误");
//				}
//			}
//			// 管理员修改他人密码不需要验证旧密码
//		} else {
//			// 普通用户操作
//			if (!isSelfOperation) {
//				throw new RuntimeException("无权限修改其他用户密码");
//			}
//			// 必须验证旧密码
//			if (dto.getOldPassword() == null) {
//				throw new RuntimeException("旧密码不能为空");
//			}
//			if (!dto.getOldPassword().equals(targetUser.getPassword())) {
//				throw new RuntimeException("旧密码错误");
//			}
//		}

		User byId = this.getById(LoginUser.getUserId());
		// 更新密码
		byId.setPassword(dto.getNewPassword());
		return updateById(byId);
	}

	/**
	 * 获取用户头像的Base64数据
	 */
	public String getAvatarBase64(String fileName) {
		try {
			if (StrUtil.isEmpty(fileName)) {
				return null;
			}

			String filePath = avatarPath + File.separator + fileName;
			if (!FileUtil.exist(filePath)) {
				return null;
			}

			byte[] fileContent = FileUtil.readBytes(filePath);
			String base64 = Base64.getEncoder().encodeToString(fileContent);

			// 获取图片类型
			String imageType = FileUtil.extName(fileName);
			return "data:image/" + imageType + ";base64," + base64;
		} catch (Exception e) {
			log.error("获取头像失败", e);
			return null;
		}
	}

	@Override
	public User createUser(User user) {
		// 检查用户名是否已存在
		if (lambdaQuery().eq(User::getUsername, user.getUsername()).exists()) {
			throw new BusinessException("用户名已存在");
		}

		// 保存用户
		save(user);
		return user;
	}

	@Override
	public boolean updateUser(User user) {
		// 检查用户名是否已存在（排除自己）
		if (lambdaQuery()
				.eq(User::getUsername, user.getUsername())
				.ne(User::getUserId, user.getUserId())
				.exists()) {
			throw new BusinessException("用户名已存在");
		}
		return updateById(user);
	}

	@Override
	public boolean deleteUser(Long userId) {
		return removeById(userId);
	}

	@Override
	public IPage<User> getUserList(Page<User> page) {
		return page(page);
	}

	@Override
	public boolean updateUserInfo(String nickname, MultipartFile avatarFile) {
		try {
			Long userId = com.orderVideo.utils.LoginUser.getUserId();
			User user = this.getById(userId);
			if (user == null) {
				throw new RuntimeException("用户不存在");
			}

			boolean needUpdate = false;

			// 更新昵称
			if (StrUtil.isNotEmpty(nickname)) {
				user.setNickName(nickname);
				needUpdate = true;
			}

			// 更新头像
			if (avatarFile != null && !avatarFile.isEmpty()) {
				try {
					String fileName = handleAvatarUpload(avatarFile);
					user.setUserImg(fileName);
					needUpdate = true;
				} catch (Exception e) {
					log.error("更新头像失败", e);
					throw new RuntimeException("更新头像失败: " + e.getMessage());
				}
			}

			return !needUpdate || this.updateById(user);
		} catch (Exception e) {
			log.error("更新用户信息失败", e);
			throw new RuntimeException("更新用户信息失败: " + e.getMessage());
		}
	}

	/**
	 * 处理头像上传的内部方法
	 */
	private String handleAvatarUpload(MultipartFile file) throws Exception {
		// 创建头像存储目录
		FileUtil.mkdir(avatarPath);

		// 获取原始文件名和扩展名
		String originalFilename = file.getOriginalFilename();
		String extension = FileUtil.extName(originalFilename);

		// 生成新文件名 (使用当前登录用户ID)
		String fileName = LoginUser.getUserId() + "." + extension;
		String filePath = avatarPath + File.separator + fileName;

		// 保存文件
		File targetFile = new File(filePath);
		file.transferTo(targetFile);

		return fileName;
	}

	/**
	 * 获取用户头像的完整路径
	 */
	public String getAvatarPath(String fileName) {
		if (StrUtil.isEmpty(fileName)) {
			return null;
		}

		String filePath = avatarPath + File.separator + fileName;
		return FileUtil.exist(filePath) ? filePath : null;
	}

	@Override
	public boolean updateUserPassword(UpdatePasswordDTO dto) {
		User user = baseMapper.selectById(dto.getUserId());
		if (user != null && StrUtil.isNotEmpty(dto.getNewPassword())) {
			user.setPassword(dto.getNewPassword());
			return updateById(user);
		}
		throw new BusinessException("用户不存在或密码为空");
	}

}




